package main

import (
	"github.com/xgdapg/wtk"
	"log"
	"net/url"
	"os"
	"path"
	"path/filepath"
	"strconv"
	"time"
)

type DbConfig struct {
	DbAddress  string
	DbUsername string
	DbPassword string
	DbName     string
	DbPrefix   string
}

type Config struct {
	AppPath    string
	BlogName   string
	BlogDesc   string
	DomainPath string
	PrefixPath string
	Theme      string
	NumPerPage int
	PwdSecret  string
	Password   string
}

func LoadSysConfig() {
	wtk.AppRoot = cfg.AppPath
	data, err := model.GetAllConfig()
	if err != nil {
		log.Println(err)
		os.Exit(-1)
	}

	if v, ok := data["BlogName"]; ok {
		cfg.BlogName = v
	} else {
		model.SetConfig("BlogName", cfg.BlogName)
	}

	if v, ok := data["BlogDesc"]; ok {
		cfg.BlogDesc = v
	} else {
		model.SetConfig("BlogDesc", cfg.BlogDesc)
	}

	if v, ok := data["DomainPath"]; ok {
		if v[len(v)-1] == '/' {
			v = v[:len(v)-1]
		}
		cfg.DomainPath = v
	} else {
		model.SetConfig("DomainPath", cfg.DomainPath)
	}
	u, err := url.Parse(cfg.DomainPath)
	if err == nil && u.Path != "/" {
		path := u.Path
		if path != "" {
			if path[0] != '/' {
				path = "/" + path
			}
			if path[len(path)-1] == '/' {
				path = path[:len(path)-1]
			}
		}
		cfg.PrefixPath = path
	}

	if v, ok := data["PwdSecret"]; ok {
		cfg.PwdSecret = v
	} else {
		uns := time.Now().UnixNano()
		cfg.PwdSecret = getHash(strconv.FormatInt(uns, 19), strconv.FormatInt(uns, 31))
		model.SetConfig("PwdSecret", cfg.PwdSecret)
	}

	if v, ok := data["Password"]; ok {
		cfg.Password = v
	} else {
		cfg.Password = getHash("123456", cfg.PwdSecret)
		model.SetConfig("Password", cfg.Password)
	}

	if v, ok := data["Theme"]; ok {
		cfg.Theme = v
	} else {
		model.SetConfig("Theme", cfg.Theme)
	}

	if v, ok := data["NumPerPage"]; ok {
		npp, err := strconv.Atoi(v)
		if err == nil {
			cfg.NumPerPage = npp
		}
	} else {
		model.SetConfig("NumPerPage", strconv.Itoa(cfg.NumPerPage))
	}

	wtk.SetTemplateVar("BlogName", cfg.BlogName)
	wtk.SetTemplateVar("BlogDesc", cfg.BlogDesc)
	wtk.SetTemplateVar("DomainPath", cfg.PrefixPath)
	wtk.SetTemplateVar("ThemeStaticPath", cfg.PrefixPath+"/"+path.Join("static", "theme", cfg.Theme))
}

func (this *Config) RootPath() string {
	return this.AppPath
}

func (this *Config) SetRootPath(p string) {
	this.AppPath = p
	wtk.AppRoot = p
}

func (this *Config) ThemeTplPath() string {
	return filepath.Join(this.AppPath, "tpl", "theme", this.Theme)
}

func (this *Config) AdminTplPath() string {
	return filepath.Join(this.AppPath, "tpl", "admin")
}
